//
//  LEEWeiboStatusesViewModel.swift
//  SinaWeibo
//
//  Created by 李江波 on 2016/11/16.
//  Copyright © 2016年 lijiangbo. All rights reserved.
//
/*
 
 ***********MVC**************
 - vc
 - tableView   [HMStatus]
 - cell    HMStatus
 -------------------------------------------
 
 **********只是处理tableView 数据***********
 - vc   -------    HMHomeViewModel
 - tableView     获取视图模型的属性(模型数组[HMStatus])
 - cell    ---  HMStatus
 
 -------------------------------------------
 
 
 ********处理cell的viewmodel 和tableView [viewmodel]*******
 - vc   -------    HMHomeViewModel
 - tableView     获取视图模型的属性(模型数组[HMStatusCellViewModel])
 - cell    ---  HMStatusCellViewModel(HMStatus)
 
 */


import UIKit
import SDWebImage


class LEEWeiboStatusesViewModel: NSObject {
    
    
    var arrayCount : Int = 0

    lazy var arrayStatuses : [LEEStatuseViewModel] = [LEEStatuseViewModel]()
     //加载微博数据
    func loadData(isPullup : Bool, completion : @escaping (_ isSuccess : Bool, _ count : Int) -> ()) {
        
        
        var max_id : Int64 = 0
        //若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博）
        var since_id : Int64 = 0
        
        if isPullup {
            //若指定此参数，则返回ID小于或等于max_id的微博
            max_id = arrayStatuses.last?.statuse?.id ?? 0
            if max_id != 0 {
            
                max_id -= 1
            }
        }else{
        //使用了since_id ，会导致中间一大段数据永远也不能访问了
            since_id = arrayStatuses.first?.statuse?.id ?? 1
        }
        
        
        LEEStatusetDAL.loadHomeData(sinceID: since_id, MAX_ID: max_id) { (array) in
            //如果数组为空  请求失败
            if array == nil {
            
                completion(false, 0)
                return
            }
            
            var arrayM = [LEEStatuseViewModel]()
                
            for item in array! {
                let weiboStatuse = LEEStatuseViewModel()
                    
                let model = LEEWeiboStatuses()
                model.yy_modelSet(with: item)
                    
                weiboStatuse.statuse = model
                
                if model.pic_urls?.count != 1 {
                
                    //优化 计算行高
                    let cell = self.loadCell(model: weiboStatuse)
                    cell.itemModel = weiboStatuse
                    cell.layoutIfNeeded()
                    weiboStatuse.rowHeight = cell.threeBtn.frame.maxY
                    
                }
                
                arrayM.append(weiboStatuse)
            }
            self.arrayCount = arrayM.count
            if isPullup {
                    
                self.arrayStatuses = self.arrayStatuses + arrayM
                    
                self.cacheStatusSingleImage(array: arrayM, completion: completion)
            }
                
            

        //只有下拉的时候运行
        if !isPullup {
            
            if arrayM.count < 20 {
            
                 self.arrayStatuses = arrayM + self.arrayStatuses
            }else {
                 self.arrayStatuses.removeAll()
                 self.arrayStatuses = arrayM
            }
            self.cacheStatusSingleImage(array: arrayM, completion: completion)

        }
    }
        
    }
    

    
    //缓存单张图片
    private func cacheStatusSingleImage(array: [LEEStatuseViewModel], completion: @escaping (_ isSuccess : Bool, _ count : Int)->()) {
    
        if array.count == 0 {
            //一定要执行回调
            completion(true, 0)
            return
        }
        //遍历视图模型
        //使用调度组 入组和出组必须成对出现,没有出组不会执行回调
        let group = DispatchGroup()
        for viewModel in array {
            if viewModel.imgUrls?.count == 1 {
                //只有一张图图片
                //执行下载图片的操作
                //异步任务 希望所有的异步任务执行完毕之后再执行回调
                //在开始异步任务之前 执行入组的操作 ,调度组中的异步任务 + 1
                group.enter()
                let url = URL(string: viewModel.imgUrls?.first?.imgUrl ?? "")
                SDWebImageManager.shared().downloadImage(with: url, options: [], progress: nil, completed: { (_, _, _, _, _) in
                    
                    print("----单张图片下载成功")
                    //出组, 标识调度组中的异步任务 -1
                    group.leave()
                })
                
                
            }
            
        }
        group.notify(queue: DispatchQueue.main) {
            for viewModel in array {
            
                if viewModel.imgUrls?.count == 1 {
                
                    //优化 计算行高
                    let cell = self.loadCell(model: viewModel)
                    cell.itemModel = viewModel
                    cell.layoutIfNeeded()
                    viewModel.rowHeight = cell.threeBtn.frame.maxY
                }
            }
            
                completion(true, self.arrayCount)

            
        }
    }
    
    private func loadCell(model : LEEStatuseViewModel) -> LEEStatuseCell {
        
        if model.statuse?.retweeted_status == nil {
            
            return orginalCell
        }
        
        return retweetedCell
    }
    

}









